<template>
    <div class="container">
        <div class="operation-wrapper">
            <el-button
                type="primary"
                size="mini"
                @click="handleResolveSubmit">保存</el-button>
        </div>
        <el-row class="form-wrapper">
            <el-col
                :sm="12"
                :md="10"
                :lg="8"
                :xl="6">
                <el-form
                    :model="titleFormData"
                    label-width="110px"
                    label-position="left"
                    size="small">
                    <el-form-item
                        label="用户分组名称"
                        prop="title">
                        <el-input v-model.trim="titleFormData.title" />
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <div class="content-wrapper">
            <div
                class="panel"
                v-for="(item, index) in resolveList"
                :key="index">
                <div class="panel-header">
                    <div class="panel-title-wrapper">
                        <span class="panel-title">{{ item.title }}</span>
                    </div>
                </div>
                <div class="panel-content">
                    <el-tree
                        :ref="`tree_${item.group_no}`"
                        v-if="item.children"
                        :data="item.children"
                        :props="{label: 'title'}"
                        node-key="auth_name"
                        :default-checked-keys="authOfUserGroup"
                        show-checkbox/>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { addAuthToGroup, extractAuth } from "@/assets/js/transform";

export default {
    data() {
        return {
            groupNo: '',
            titleFormData: {
                title: ''
            },
            authGroupList: [], // 权限分组原始数据
            authList: [], // 权限原始数据
            resolveList: [], // 权限及分组融合后的列表，用于渲染页面使用
            authOfUserGroup: [], // 已授权权限，编辑用
        };
    },
    created() {
        let { group_no } = this.$route.query;

        this.groupNo = group_no || '';
        this.init();
        this.$store.commit('SET_HEADER', [
            {
                title: '设置',
            },
            {
                title: '用户组列表',
                name: 'UserGroupList'
            },
            {
                title: this.groupNo ? '编辑' : '新增'
            }
        ]);
    },
    methods: {
        /**
         * 初始化
         */
        init() {
            this.getAuthGroup(() => {
                this.getAuthList();
            });
            if (this.groupNo) {
                this.getInfoOfUserGroup();
            }
        },

        /**
         * 获取权限分组
         */
        getAuthGroup(callback) {
            this.$post('/__local/system%5Cauth_group%5Cget_list', {}, resp => {
                if (resp.code == 1) {
                    if (Array.isArray(resp.data.list)) {
                        this.authGroupList = resp.data.list;
                    } else {
                        this.groupList = [];
                    }
                    if (callback) {
                        callback();
                    }
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg || '获取权限分组失败，请刷新重试'
                    });
                }
            });
        },

        /**
         * 获取权限
         */
        getAuthList() {
            this.$post('/__local/system%5Cauth%5Cget_list', {}, resp => {
                if (resp.code == 1) {
                    this.authList = resp.data.list;

                    let group = [].concat(this.authGroupList);
                    let auth = [].concat(this.authList);
                    let { resolve, left } = addAuthToGroup(group, auth);

                    resolve.push({
                        create_time: 0,
                        title: '未分组',
                        prarent_group_no: '',
                        group_no: 'not_sorted',
                        children: left
                    });

                    this.resolveList = resolve;
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg || '获取权限列表失败，请刷新重试'
                    });
                }
            });
        },

        /**
         * 获取用户组信息，包括用户组名称和已有的权限
         */
        getInfoOfUserGroup() {
            this.$post('/__local/system%5Cuser_group%5Cget', {
                group_no: this.groupNo
            }, resp => {
                if (resp.code == 1) {
                    this.titleFormData.title = resp.data.title;
                    this.authOfUserGroup = resp.data.auth_name_list;
                }
            });
        },

        /**
         * 提交前处理
         */
        handleResolveSubmit() {
            if (!this.titleFormData.title) {
                this.$message({
                    type: 'warning',
                    message: '请输入用户组名称'
                });
                return;
            }
            let arr = [];
            let result = [];

            for (let i in this.resolveList) {
                arr = arr.concat(this.$refs[`tree_${this.resolveList[i].group_no}`][0].getCheckedNodes());
            }

            for (let i in arr) {
                if (arr[i].auth_name) {
                    result.push({
                        auth_name: arr[i].auth_name
                    });
                }
            }

            if (this.groupNo) {
                this.submitEditUserGroup({
                    group_no: this.groupNo,
                    title: this.titleFormData.title,
                    auth_name_data: JSON.stringify(arr)
                });
            } else {
                this.submitAddUserGroup({
                    title: this.titleFormData.title,
                    auth_name_data: JSON.stringify(arr)
                });
            }
        },

        /**
         * 新增用户分组
         */
        submitAddUserGroup(obj) {
            this.$post('/__local/system%5Cuser_group%5Cadd', obj, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    });
                    this.$router.push({
                        name: 'UserGroupList'
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp || '保存失败'
                    });
                }
            });
        },

        /**
         * 编辑用户分组
         */
        submitEditUserGroup(obj) {
            this.$post('/__local/system%5Cuser_group%5Cset', obj, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp || '保存失败'
                    });
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.operation-wrapper {
    display: flex;
    flex-direction: row-reverse;
    padding: 12px 23px;
    background-color: #fff;
}
.form-wrapper {
    padding-left: 15px;
    padding-bottom: 10px;
    background-color: #fff;

    .el-form-item {
        margin-bottom: 0;
    }
}
.content-wrapper {
    flex: 1;
    padding: 15px;
    font-size: 0;
    white-space: nowrap;
    overflow-x: auto;
    overflow-y: hidden;
}
.panel {
    position: relative;
    display: inline-block;
    width: 345px;
    height: 100%;
    margin-right: 20px;
    padding-top: 45px;
    font-size: 14px;
    background-color: #fff;
    border-radius: 2px;
    border: 1px solid #ebebeb;
    vertical-align: top;
}
.panel-header {
    position: absolute;
    top: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 15px;
    line-height: 45px;
    background-color: #f7f7f7;
}
.panel-content {
    height: 100%;
    padding: 20px;
    overflow: auto;
}
</style>